import axios from 'axios'
import useToken from '../stores/token.js'
import {ElLoading} from 'element-plus'
import config from '../config.js'
import notification from './notification.js'
import router from '../router/index.js'

const baseURL = config.baseUrl
var loadingInstance = null
const service =axios.create({baseURL})

service.interceptors.request.use(config=>{
    loadingInstance = ElLoading.service()
    const {token} = useToken()
    if (token) {
        config.headers.jwt=token
    }
    return config
})

service.interceptors.response.use(
    response=> {
        loadingInstance.close()
        const {errno, data, errmsg} = response.data
        if (errno === 0) {
            if (errmsg !== '') {
                notification({
                    message: 'errmsg',
                    type: 'success'
                })
            }
            return data || true
        }
        notification({
            message: 'errmsg',
            type: 'error'
        })
        if (errno === 2) {
            router.push({name: 'login'})
        }
        return false
    },
    error=>{
        loadingInstance.close()
        notification({
            message:'请求失败',
            type:'error'
        })
        console.log()
    }
)
export default service
